<template>
	<view class="">
		<view class="" style="
        height: 264rpx;
        padding: 0 52rpx 0 7rpx;
        align-items: center;
        display: flex;
        justify-content: space-between;
        font-size: 24rpx;
      ">
			<view class="">
				<uni-icons custom-prefix="back" type="back" @click="Black" size="48rpx"></uni-icons>
			</view>
			<view class="">
				{{ obj == null ? "添加档案" : "修改档案" }}
			</view>
			<view class=""> </view>
		</view>

		<view class="wrap">
			<view class="addImg">
				<image @tap="uploadImg" :src="form.avatar" mode="aspectFill" lazy-load="false" />
				<view class="avatar">上传头像</view>
			</view>
			<view class="iptSyl">
				<van-field input-align="right" :value="form.realname" placeholder="请输入昵称(最多输入6个字)" label="昵称"
					@change="getNickname" />
				<van-cell title="关系" is-link :value="form.relation" @tap="openRalation" v-if="isyou" />
				<van-cell title="性别">
					<view class="sexWrap">
						<view class="sex" @tap="changeSex('1')" :style="{
                border: form.sex == 1 ? '1px solid #FF7F22' : none,
                color: form.sex == 1 ? '#FF7F22' : '#000',
              }">男</view>
						<view class="sex" @tap="changeSex('2')" :style="{
                border: form.sex == 2 ? '1px solid #FF7F22' : none,
                color: form.sex == 2 ? '#FF7F22' : '#000',
              }">女</view>
					</view>
				</van-cell>
				<van-cell title="出生时间(阳历)" is-link :value="form.birthdayNew" @tap="openChooseBirth('news')" />
				<van-cell title="出生时间(农历)" :value="form.birthdayOld" />
				<van-cell title="出生地点" is-link :value="form.birthAddr" @tap="openChooseAddr('oldAddr')" />
				<van-cell title="现居城市" is-link :value="form.nowAddr" @tap="openChooseAddr('newAddr')" />
				<!-- <view class="btn"><van-button  style="width: 690rpx;" block color="#FF7F22" size="small" @tap="saveData">保存</van-button></view> -->
				<view class="btn">
					<button class="footer_btn" @tap="saveData">保存</button>
				</view>
				<!-- 出生时间选择 -->
				<van-popup :show="birthdayNewShow" round closeable position="bottom" custom-style="height: 660rpx"
					@close="onClose">
					<view class="title">{{
            type == "news" ? "出生时间(阳历)" : "出生时间(农历)"
          }}</view>
					<view class="show">
						<view>年</view>
						<view>月</view>
						<view>日</view>
						<view>时</view>
						<view>分</view>
					</view>
					<view class="boxWrap">
						<van-datetime-picker style="margin-top: 40rpx" :show-toolbar="disabledToolbar" type="datetime"
							:value="currentDate" :min-date="minDate" :max-date="maxDate" @input="onInput" />
					</view>

					<view class="saveBtn" style="padding: 30rpx" @tap="getTimer">
						<van-button type="primary" block color="#FF7F22">完成</van-button>
					</view>
				</van-popup>
				<!-- 出生地点选择 -->
				<van-popup :show="addrShow" round closeable position="bottom" custom-style="height: 660rpx"
					@close="onClose">
					<view class="title">{{
            addrType == "oldAddr" ? "出生地点" : "现居城市"
          }}</view>
					<view style="height: 400rpx; overflow: hidden">
						<van-area :show-toolbar="disabledToolbar" :area-list="areaList" @change="getAddr" />
					</view>
					<view class="saveBtn" style="padding: 30rpx" @tap="saveAddr">
						<van-button type="primary" block color="#FF7F22">完成</van-button>
					</view>
				</van-popup>

				<!-- 关系选择 -->
				<van-popup :show="relationShow" round closeable position="bottom" custom-style="height: 440rpx"
					@close="onClose">
					<view class="title">请选择分类</view>
					<view style="
              height: 160rpx;
              overflow: hidden;
              display: flex;
              justify-content: space-between;
              margin: 30rpx;
              flex-wrap: wrap;
            ">
						<view class="relationBtn" :style="{
                color: current == idx ? '#FF7F22' : '#222229',
                border: current == idx ? '1px solid #FF7F22' : 'none',
                width: current == idx ? '126rpx' : '130rpx',
                height: current == idx ? '60rpx' : '64rpx',
                'line-height': current == idx ? '60rpx' : '64rpx',
              }" v-for="(item, idx) in relationArr" :key="idx" @tap="choosedRelation(idx)">
							{{ item.itemValue }}
						</view>
					</view>
					<view class="saveBtn" style="padding: 30rpx" @tap="saveRelation">
						<van-button type="primary" block color="#FF7F22">完成</van-button>
					</view>
				</van-popup>
				<van-toast id="van-toast" />
			</view>
		</view>
	</view>
</template>
<script>
	import moment from "moment";
	import {
		areaList
	} from "@vant/area-data";
	import Toast from "../../../wxcomponents/@vant/weapp/toast/toast";
	import {
		baseURL
	} from "../../../utils/baseUrl";
	import {
		imgBaseUrl
	} from "../../../utils/baseUrl.js";
	import {
		getRelationalListAPI,
		addRecordAPI,
		// checkImgAPI
	} from "../../../utils/api";
	import {
		queryUserIsDetails
	} from "../../../utils/myapi";
	import {
		userDetailsedit
	} from "../../../utils/OnetoOneaApi.js";
	import {
		Solar,
		Lunar,
		HolidayUtil
	} from 'lunar-javascript';
	export default {
		data() {
			return {
				minHour: 10,
				maxHour: 20,
				baseURL: "",
				minDate: new Date(1970).getTime(),
				maxDate: new Date().getTime(),
				currentDate: new Date().getTime(),
				birthdayNewShow: false, // 出生日期是否打开弹框
				addrShow: false, // 地址是否打开弹框
				disabledToolbar: false, // 禁用Toolbar
				relationShow: false, // 关系是否打开弹框
				type: "news", // news出生时间公历 old出生时间农历
				addrType: "oldAddr", // oldAddr出生地  newAddr现居住地
				currentTime: "", // 临时存储选中时间
				currentAddr: "", // 临时存储地点
				currentRelation: "", // 临时存储关系信息
				current: 0, //关系默认选择
				areaList,
				relationArr: [],
				form: {
					avatar: imgBaseUrl + "/img/allImgs/record/addImg.svg",
					realname: "",
					relation: "请选择",
					sex: 1,
					birthdayNew: "",
					birthdayOld: "",
					birthAddr: "",
					nowAddr: "",
				},
				addstatus: "",
				id: "",
				usid: "", //用户id
				relationship: "",
				isyou: true,
				obj: {},
				isucess: true
			};
		},
		onLoad(detail) {
			console.log(detail, "ddddd");
			this.usid = detail.userid; //获取用户id
			this.baseURL = baseURL;
			this.form.avatar =
				detail.imgurl == "null" ?
				imgBaseUrl + "/img/allImgs/record/addImg.svg" :
				detail.imgurl == undefined ?
				imgBaseUrl + "/img/allImgs/record/addImg.svg" :
				detail.imgurl;
			this.id = detail.Id;
			this.addstatus = detail.status;
			this.form.realname = detail.realname;
			this.form.relation =
				detail.relationship == undefined ? "本人" : detail.relationship;
			this.form.sex = detail.sex ? Number(detail.sex) : 1;
			this.form.birthdayNew = detail.birthday;
			this.form.birthdayOld = detail.lunarBirthday;
			this.form.birthAddr = detail.birthPlace == "null" ? "" : detail.birthPlace;
			this.form.nowAddr =
				detail.currentAddress == "null" ? "" : detail.currentAddress;
			if (detail.relationship == "本人") {
				this.isyou = false;
			}
		},
		onShow() {
			this.relationList();
			console.log(this.usid, "usid");
		},
		mounted() {
			if (this.usid != undefined || this.addstatus == "add") {
				this.querymessage();
			}
		},
		methods: {
			//查询是否有本热档案
			async querymessage() {
				const res = await queryUserIsDetails(this.usid);
				this.obj = res.result;
				if (res.result != null) {
					let data = res.result;
					this.addstatus = "update";
					this.baseURL = baseURL;
					this.form.avatar =
						data.avatar == undefined ?
						imgBaseUrl + "/img/allImgs/record/addImg.svg" :
						data.avatar;
					this.id = data.id;
					this.form.realname = data.realname;
					this.form.relation =
						data.relationship == undefined ? "本人" : data.relationship;
					this.form.sex = data.sex ? Number(data.sex) : 1;
					this.form.birthdayNew = data.birthday;
					this.form.birthdayOld = data.lunarBirthday;
					this.form.birthAddr = data.birthPlace;
					this.form.nowAddr = data.currentAddress;
					if (data.relationship == "本人") {
						this.isyou = false;
					}
				} else {
					this.isyou = true;
				}
			},
			// 查询关系
			async relationList() {
				const relationRes = await getRelationalListAPI();
				this.relationArr = relationRes.result;
			},
			// 保存数据
			async saveData() {
				console.log(this.form.avatar, "this.form.avatar");
				// const avindex = this.form.avatar.indexOf("/",this.form.avatar.lastIndexOf("/"))
				const avindex = this.form.avatar.lastIndexOf("/");
				let avpath = this.form.avatar.substring(avindex + 1);
				const params = {
					birthPlace: this.form.birthAddr,
					birthday: this.form.birthdayNew == "" || this.form.birthdayNew == undefined ?
						"" :
						this.form.birthdayNew + ":00",
					currentAddress: this.form.nowAddr,
					avatar: avpath == "addImg.svg" ? "" : avpath,
					lunarBirthday: this.form.birthdayOld,
					realname: this.form.realname,
					relationship: this.form.relation,
					sex: this.form.sex,
				};
				if (this.addstatus == "update") {
					params["id"] = this.id;
				}
				if (this.isucess) {
					this.isucess = false
					let _this = this
					setTimeout(() => {
						_this.isucess = true
					}, 1000)
					try {
						if (this.addstatus == "update") {
							const res = await userDetailsedit(params);
							if (res.code == 200) {
								Toast.success("修改成功");
								if (params.relationship == '本人') {
									uni.setStorageSync("userInfo", res.result);
								}
								setTimeout(() => {
									uni.navigateBack(-1);
								}, 500);
							}
						} else {
							const res = await addRecordAPI(params);
							if (res.code == 200) {
								Toast.success("添加成功");
								if (this.form.relation == "本人") {
									uni.setStorageSync("userInfo", res.result);
								}
								if (this.addstatus == "add") {
									uni.navigateBack(-1);
								} else {
									setTimeout(() => {
										uni.navigateBack(-1);
									}, 2000);
								}
							} else {
								Toast.error(res.message);
							}
						}
					} catch (error) {}
					}
				
			},

			// 给出生时间赋值
			getTimer() {
				if (this.type == "news") {
					this.form.birthdayNew = moment(this.currentTime).format("YYYY-MM-DD HH:mm");
					const lunarDate = Lunar.fromDate(new Date(this.currentTime));
					const time = lunarDate.getTimeInGanZhi();
					this.form.birthdayOld = String(lunarDate) + time
				}
				this.birthdayNewShow = false;
			},

			// 弹出地点弹出框
			openChooseAddr(type) {
				this.addrType = type;
				this.addrShow = true;
			},

			// 存储地点
			saveAddr() {
				if (this.addrType == "oldAddr") {
					this.form.birthAddr =
						this.currentAddr == "" ? "北京市 北京市 东城区" : this.currentAddr;
				} else {
					this.form.nowAddr =
						this.currentAddr == "" ? "北京市 北京市 东城区" : this.currentAddr;
				}
				this.addrShow = false;
			},
			// 获取地点
			getAddr(e) {
				let arr = e.detail.values.map((vls) => {
					return vls.name;
				});
				this.currentAddr = arr.join(" ");
			},

			// 打开关系弹窗
			openRalation() {
				this.relationShow = true;
			},

			// 选择关系
			choosedRelation(idx) {
				this.current = idx;
				this.currentRelation = this.relationArr[idx].itemValue;
			},

			//  存储关系
			saveRelation() {
				console.log("this.currentRelation", this.relationArr[0]);
				this.form.relation =
					this.currentRelation == "" ?
					this.relationArr[0].itemValue :
					this.currentRelation;
				this.relationShow = false;
			},

			// 打开弹出框显示出生日期
			openChooseBirth(type) {
				this.type = type;
				this.birthdayNewShow = true;
			},

			// 关闭弹窗
			onClose() {
				this.birthdayNewShow = false;
				this.addrShow = false;
				this.relationShow = false;
			},
			// 获取选择的时间
			onInput(e) {
				this.currentTime = e.detail;
			},
			// 获取性别
			changeSex(sex) {
				this.form.sex = sex;
			},
			// 获取昵称
			getNickname(e) {
				console.log("e", e);
				let font = e.detail;
				if (font.length == 6) {
					uni.showToast({
						icon: "none",
						title: "最多输入6个字！",
					});
				}
				this.form.realname = font.slice(0, 6);
			},
			// 上传头像
			uploadImg() {
				let _this = this;

				uni.chooseImage({
					count: 1, //默认9
					sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album"], //从相册选择
					success: async function(res) {
						uni.showLoading({
							title: "加载中",
						});
						uni.uploadFile({
							url: baseURL + "/sys/common/upload",
							filePath: res.tempFilePaths[0],
							header: {
								"X-Access-Token": uni.getStorageSync("token"),
							},
							name: "file",
							success: async (uploadFileRes) => {
								console.log("uploadFileRes", JSON.parse(uploadFileRes.data));
								const img = JSON.parse(uploadFileRes.data);
								console.log(img.message, "message");
								// await checkImgAPI(img.message,"帖子")
								_this.form.avatar = baseURL + "/" + img.message;
								uni.hideLoading();
							},
							fail: (fail) => {
								console.log("fail", fail);
							},
						});
						_this.form.avatar = res.tempFilePaths[0];
					},
				});
			},
			//返回
			Black() {
				uni.navigateBack(-1);
				this.obj = {};
			},
		},
	};
</script>
<style lang="less">
	.relationBtn {
		// width: 130rpx !important;
		// height: 64rpx;
		// line-height: 64rpx;
		text-align: center;
		background: #f8f8f9;
		border-radius: 4rpx;
		width: 48rpx;
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #222229;
	}

	.title {
		text-align: center;
		margin-top: 30rpx;
	}

	.show {
		margin-bottom: 40rpx;
		margin-top: 40rpx;
		display: flex;
		justify-content: space-around;
		color: #222229;
	}

	.boxWrap {
		height: 300rpx;
		overflow: hidden;
	}

	.iptSyl {
		margin-top: 96rpx;
	}

	.sexWrap {
		display: flex;

		.sex {
			width: 158rpx;
			line-height: 44rpx;
			background: #f8f8f9;
			border-radius: 4rpx;
			text-align: center;
			color: #000;
			margin-left: 20rpx;
		}
	}

	.addImg {
		text-align: center;

		image {
			width: 128rpx;
			height: 128rpx;
			border-radius: 50%;
		}

		.avatar {
			font-size: 32rpx;
			margin-top: 24rpx;
		}
	}

	.wrap {
		padding: 0 30rpx;
	}

	.btn {
		margin: 30rpx 0;
		display: flex;
		justify-content: flex-end;

		button {
			width: 100% !important;
		}

		.footer_btn {
			background: #ff7f22;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			opacity: 1;
			color: #ffffff;
		}
	}
</style>